package patrol.mobile.com.mobilepatrol.activity.bridge;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.VideoView;

import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.adapter.BridgeTrackListAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.Qiaoliang;
import patrol.mobile.com.mobilepatrol.bean.QldqjcBjjcb;
import patrol.mobile.com.mobilepatrol.bean.QldqjcBjqsb;
import patrol.mobile.com.mobilepatrol.bean.QldqjcBjqstpb;
import patrol.mobile.com.mobilepatrol.bean.Qldqjcb;
import patrol.mobile.com.mobilepatrol.bean.Qljcxjcb;
import patrol.mobile.com.mobilepatrol.manager.QManager;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.persenter.QHUpPer;
import patrol.mobile.com.mobilepatrol.persenter.UploadPicsPresenter;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.view.BridgeUpView;
import patrol.mobile.com.mobilepatrol.view.UploadImgView;

import static patrol.mobile.com.mobilepatrol.PatrolApp.realm;
import static patrol.mobile.com.mobilepatrol.R.mipmap.upload;

/**
 * Created by apple on 17/9/29.
 */

public class BridgeListActivity extends BaseActivity implements BridgeUpView ,UploadImgView {
    @BindView(R.id.iv_end_title)
    ImageView iv_end_title;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    private BridgeTrackListAdapter mAdapter;
    private List<Qiaoliang> mList = new ArrayList<>();
    private ArrayList<Qldqjcb> upList_dq;
    private ArrayList<Qljcxjcb> upList_jc;
    private ArrayList<QldqjcBjqstpb> upList_tp;
    private List<String> upqlcodes;
    @BindView(R.id.iv)
    ImageView iv;
    public boolean selAll;
    @Override
    public void initView() {
        //super的重要性
        super.initView();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new BridgeTrackListAdapter(this, mList);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mList = QManager.getQList2();
        QManager.setcbState(mList,false);
        mAdapter.updateItems(mList);
    }

    @Override
    public void initData() {
        mList = QManager.getQList2();
        QManager.setcbState(mList,false);
        mAdapter.updateItems(mList);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(BridgeListActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("桥梁巡查");
        iv_end_title.setVisibility(View.VISIBLE);
        iv_end_title.setImageResource(R.mipmap.qrcode);
        iv_end_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(ScanActivity.class);
                CommonUtil.openNewActivityAnim(BridgeListActivity.this, false);
            }
        });
        iv_right_title.setVisibility(View.VISIBLE);
        iv_right_title.setImageResource(upload);
        iv_right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 upqlcodes = mAdapter.getQlcodes();
                if (upqlcodes == null || upqlcodes.size() == 0) {
                    showToast2("请选择桥梁");
                    return;
                }
                showLoading();
                upList_dq = new ArrayList<Qldqjcb>();
                upList_jc = new ArrayList<Qljcxjcb>();
                upList_tp = new ArrayList<QldqjcBjqstpb>();
                //多少个桥
                for (int i = 0; i < upqlcodes.size(); i++) {
                    //每个桥的定期检查列表
                    List<Qldqjcb> trans_dq = new ArrayList<Qldqjcb>();
                    List<Qljcxjcb> trans_jc = new ArrayList<Qljcxjcb>();
                    List<QldqjcBjqstpb> trans_tp = new ArrayList<QldqjcBjqstpb>();
                    List<Qldqjcb> dps = QManager.getBridegDQListNoUp(upqlcodes.get(i));
                    List<Qljcxjcb> jcs = QManager.getBridegJCListNoUp(upqlcodes.get(i));
                    List<QldqjcBjqstpb> tps = QManager.getBridgeNoupTps(upqlcodes.get(i));
                    if (jcs != null && jcs.size() > 0) {
                        trans_jc = realm.copyFromRealm(jcs);
                        upList_jc.addAll(trans_jc);
                    }
                    if (dps != null && dps.size() > 0) {
                        trans_dq = realm.copyFromRealm(dps);
                        upList_dq.addAll(trans_dq);
                    }
                    if (tps!=null&&tps.size()>0){
                        trans_tp = realm.copyFromRealm(tps);
                        upList_tp.addAll(trans_tp);
                    }

                }
                if (upList_tp!=null&&upList_tp.size()>0){
                    uploadImg(upList_tp);
                }else{
                    showToast2("没有可上传的图片");
                }

                uploadJC(upList_jc);
                uploadDQ(upList_dq);

            }
        });

    }

    private void uploadDQ(List<Qldqjcb> upList_dq) {
        if (upList_dq != null && upList_dq.size() > 0) {
//            //桥梁定期检查图片表
//            upImgs(upList_dq);
            Map<String, Object> map = new HashMap<>();
            /**
             * list转jsonarray
             * string转jsonarray
             */
            JsonArray jsonArray = new Gson().toJsonTree(upList_dq, new TypeToken<List<Qldqjcb>>() {
            }.getType()).getAsJsonArray();

            map.put("userName", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).username);
            map.put("passWord", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).pw);
            map.put("qldqjc", jsonArray);
            /**
             * map转json字符串
             */
            String obj2 = GsonUtil.GsonString(map);
            Logger.d(obj2);
            QHUpPer per = new QHUpPer(BridgeListActivity.this, obj2);
            per.up2(Urls.addQldqjc);
        } else {
            hideLoading();
            showToast2("没有定期检查列表");
        }
    }

//    private void upImgs(List<Qldqjcb> upList_dq) {
//        List<QldqjcBjqstpb> uptps = new ArrayList<>();
//        //一个桥梁有多个定期检查对象，这个列表是多个桥梁的多个定期检查对象
//        for(int i=0;i<upList_dq.size();i++){
//            Qldqjcb dq = upList_dq.get(i);
//            List<QldqjcBjqstpb> tps = QManager.getBridgeDQNoupTps(dq.qldqjcid);
//            uptps.addAll(tps);
//
//        }
//        if (uptps.size()>0){
//            uploadImg(uptps);
//        }else{
//            showToast2("没有可上传图片");
//        }
//    }

    private void uploadJC(List<Qljcxjcb> upList_jc) {
        if (upList_jc != null && upList_jc.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            /**
             * list转jsonarray
             * string转jsonarray
             */
            JsonArray jsonArray = new Gson().toJsonTree(upList_jc, new TypeToken<List<Qldqjcb>>() {
            }.getType()).getAsJsonArray();

            map.put("userName", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).username);
            map.put("passWord", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).pw);
            map.put("qljcxjc",jsonArray);
            /**
             * map转json字符串
             */
            String obj2 = GsonUtil.GsonString(map);
            Logger.d(obj2);
            QHUpPer per = new QHUpPer(BridgeListActivity.this, obj2);
            per.up2(Urls.addQljcxjc);

//            QHUpPer per = new QHUpPer(BridgeListActivity.this, map);
//            per.up3(Urls.addQljcxjc);

        } else {
            hideLoading();
            showToast2("没有经常检查列表");
        }
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.comment_list_all;
    }

    @Override
    public void setListener() {
        mAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(BridgeListActivity.this, BridgeDetailActivity.class);
                intent.putExtra("list", true);
                intent.putExtra("qlcode", mList.get(position).qlcode);
                startActivity(intent);
                CommonUtil.openNewActivityAnim(BridgeListActivity.this, false);
            }
        });
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //原来是全选
                if (selAll){
                    unSel();
                }else{
                    selAll();
                }

            }
        });
    }

    @Override
    public void onError(String s) {
        hideLoading();
        showToast2(s);
    }

    @Override
    public void onSuccess(String s) {
        hideLoading();
        showToast2(s);
        if (upqlcodes != null && upqlcodes.size() > 0) {

            for (int i=0;i<upqlcodes.size();i++){
                List dqs = QManager.getBridegDQListNoUp(upqlcodes.get(i));
                List jcs = QManager.getBridegJCListNoUp(upqlcodes.get(i));
                if ((dqs!=null&&dqs.size()>0)||(jcs!=null&&jcs.size()>0)){
                    QManager.setQLUpState(upqlcodes.get(i),true);
                }

            }
        }
        if (upList_dq != null && upList_dq.size() > 0) {

            for (int i=0;i<upList_dq.size();i++){
                QManager.setBridegDQListUpState(upList_dq.get(i).qlcode,true);
                List<QldqjcBjqsb> qs = upList_dq.get(i).bjqs;
                for (int j=0;j<qs.size();j++){
                    QManager.setQldqjcBjqsbListUpState(qs.get(j).qldqjcid,true);
                }

                List<QldqjcBjjcb> jc = upList_dq.get(i).bjjc;
                for (int j=0;j<jc.size();j++){
                    QManager.setQldqjcBjjcbUpState(jc.get(j).qldqjcid,true);
                }

            }
        }
        if (upList_jc != null && upList_jc.size() > 0) {
            for (int i=0;i<upList_jc.size();i++){
                QManager.setBridegJCListUpState(upList_jc.get(i).qlcode,true);

            }
        }

        mList = QManager.getQList2();
        mAdapter.updateItems(mList);

    }
    public void selAll(){
        selAll = true;
        QManager.setcbState(mList,true);
        mList = QManager.getQList2();
        mAdapter.updateItems(mList);
        iv.setImageResource(R.mipmap.sel);
    }
    public void unSel(){
        selAll = false;
        QManager.setcbState(mList,false);
        mList = QManager.getQList2();
        mAdapter.updateItems(mList);
        iv.setImageResource(R.mipmap.unsel);
    }
    //根据列表cb控制全选cb，只是ui上的变化
    public void num(int style,int b,String hdcode){
        switch (style){
            //加
            case 0:
                if (b==mList.size()){
                    iv.setImageResource(R.mipmap.sel);
                }
                break;
            //减
            case 1:
                iv.setImageResource(R.mipmap.unsel);
                break;
        }
    }
    public void specialUpdate(final int sytle, final int b, final String hdcode) {
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int b = msg.arg1;
                int style = msg.arg2;
                String hdcode = (String) msg.obj;
                num(style,b,hdcode);
            }
        };


        final Runnable r = new Runnable() {
            public void run() {
                Message msg = handler.obtainMessage();
                msg.arg1 = b;
                msg.obj = hdcode;
                msg.arg2 = sytle;
                handler.sendMessage(msg);
            }
        };
        handler.post(r);
    }
//    public void uploadFile(final QldqjcBjqstpb tp) {
//        showLoading();
//        String imgname;
//        File file = new File(tp.bdcfdz);
//        if (!file.exists()) {
////            showToast("没有图片");
//        }else{
//            //根据tpbm拿到图片，目前一个部件缺损有一张图片
//            RealmResults<QldqjcBjqstpb> tps = realm.where(QldqjcBjqstpb.class).equalTo("tpbm", tp.tpbm).findAll();
//            //修改图片名称
//            if (tps != null && tps.size() > 0 && !tps.get(0).fjmc.equals("")) {
//                imgname = tps.get(0).fjmc;
//            } else {
//                imgname = file.getName();
//            }
//            Map<String, String> params = new HashMap<>();
//            params.put("userName", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).username);
//            params.put("passWord", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).pw);
////        Logger.d(images);
//            Logger.d(file.getName());
//            OkHttpUtils.post()//
//                    .addFile("upfile", imgname, file)//
//                    .url(SPUtils.get(Constants.current_ser, "") + Urls.uploadTp)//
//                    .params(params)//
////                .headers(headers)//
//                    .build()//
//                    .execute(new StringCallback() {
//                        @Override
//                        public void onError(Call call, Exception e, int id) {
//                            showToast2("图片上传失败");
//                        }
//
//                        @Override
//                        public void onResponse(String response, int id) {
//                            try {
//                                JSONObject obj = new JSONObject(response);
//                                int state = obj.optInt("state");
//                                final String imgname = obj.getString("fileName");
//                                if (state == 200) {
//
//                                    realm.executeTransaction(new Realm.Transaction() {
//
//                                        @Override
//                                        public void execute(Realm realm) {
//                                            //根据tpbm拿到图片，目前一个部件缺损有一张图片
//                                            RealmResults<QldqjcBjqstpb> tps = realm.where(QldqjcBjqstpb.class).equalTo("tpbm", tp.tpbm).findAll();
//                                            //修改图片名称
//                                            if (tps != null && tps.size() > 0) {
//                                                tps.get(0).fjmc = imgname;
//                                                tps.get(0).isUp = true;
//                                            }
//                                        }
//                                    });
//                                    showToast2("图片上传成功");
//                                }
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//
//                        }
//                    });
//        }
//
//    }
    /**
     * 上传多张图片
     */
    private void uploadImg(List<QldqjcBjqstpb> imageList) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .addFormDataPart("userName", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).username)
                .addFormDataPart("passWord",UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).pw);
        //多张图片
        for (int i = 0; i < imageList.size(); i++) {
            File file = new File(imageList.get(i).bdcfdz);//filePath 图片地址
            String filename = file.getName();
            filename = filename.substring(filename.lastIndexOf("."));
            Log.d("shj--",filename);
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("files", imageList.get(i).tpbm+filename, imageBody);//"imgfile"+i 后台接收图片流的参数名
        }

        List<MultipartBody.Part> parts = builder.build().parts();
        UploadPicsPresenter picsPresenter = new UploadPicsPresenter(this,parts);
        picsPresenter.uploadPic();

    }

    @Override
    public void upImgSuccess(String s) {
        showToast2("图片上传成功");
        QManager.alterTpUpState(upList_tp,true);
    }

    @Override
    public void upImgError(String s) {
        showToast2(s);
    }
}
